<?php

class BaseDb {

    public $pdo;

    public function query($sql) {
        try {
            $query = $this->pdo->query($sql);
            $query->setFetchMode(PDO::FETCH_ASSOC);
            $rs = $query->fetchAll();
            return $rs;
        }
        catch (PDOException $e) {
            echo 'query fail  sql:' . $sql . ' exception:' . $e->getMessage() . "\n";
            return false;
        }
        return $query;
    }

    public function queryFirst($sql) {
        try {
            $query = $this->pdo->query($sql);
            $query->setFetchMode(PDO::FETCH_ASSOC);
            $rs = $query->fetch();
            return $rs;
        }
        catch (PDOException $e) {
            echo 'query fail  sql:' . $sql . ' exception:' . $e->getMessage() . "\n";
            return false;
        }
        return $query;
    }

    public function transexec($sqls) {
        try {
            $this->pdo->beginTransaction();
            foreach ($sqls as $s) {
                $result = $this->pdo->prepare($s);
                $result->execute();
            }
            $this->pdo->commit();
        }
        catch (PDOException $e) {
            $this->pdo->rollback();
            echo 'query fail  sql:' . json_encode($sqls) . ' exception:' . $e->getMessage() . "\n";
            return false;
        }
        return true;
    }

    //事务，影响行数必须大于1
    public function forcetransexec($sqls) {
        try {
            $this->pdo->beginTransaction();
            foreach ($sqls as $s) {
                $result = $this->pdo->prepare($s);
                $result->execute();
                if ($result->rowCount() == 0) {
                    $this->pdo->rollback();
                    echo 'query fail sql:' . json_encode($s) . ' exception:' . "影响行数为0\n";
                    return false;
                }
            }
            $this->pdo->commit();
        }
        catch (PDOException $e) {
            $this->pdo->rollback();
            echo 'query fail sql:' . json_encode($sqls) . ' exception:' . $e->getMessage() . "\n";
            return false;
        }
        return true;
    }

    public function exec($sql) {
        $result = $this->pdo->prepare($sql);
        $res = $result->execute();
        return $res;
    }

}
